# -*- coding: UTF-8 -*-
import utime as time

import checkNet as cn
import dataCall as dc

_4g_connected = False

def singleton(cls, *args, **kw):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        checknet = cn.CheckNetwork("xxxx","v1.0")
        instances[cls]._stagecode,instances[cls]._subcode = checknet.wait_network_connected(30)
        return instances[cls]
    return getinstance


def _on_4g_cb(data):
    print('Get 4g CallBack for wifi.py')
    _4g_connected = True    
    pdp = data[0]
    netwk_sta = data[1]
    if netwk_sta == 1:
        print('*** network {} connected! ***'.format(pdp))
    else:
        print('*** network {} not connected! ***'.format(pdp))


@singleton
class NetWorkClient:

    """
    该模块实现网络管理相关的功能，包括初始化，联网，状态信息等.
    """
    global _on_4g_cb
    _callback = _on_4g_cb
    _stagecode = None
    _subcode = None
    def __init__(self):
      # checknet = cn.CheckNetwork("xxxx","v1.0")
      # self._stagecode,self._subcode = checknet.wait_network_connected(30)
      self.profileidx = 1
      self.ipType = 0
      self.apn = "CMNET"
      self.username = ""
      self.password = ""
      self.authType = 1
      return None

    def __str_is_empty(self,value):
        if value is None or value == "":
            return True
        else:
            return False

    def connect(self,data):
        """
        连接网络

        :param data(dict): data的key信息如下

            .. list-table::

                * - 属性
                  - 类型
                  - 必填
                  - 说明
                * - ssid
                  - 字符串
                  - 必填
                  - 需要连接的wifi热点名称
                * - password
                  - 字符串
                  - 必填
                  - 需要连接的wifi密码


            使用示例::

                # -*- coding: UTF-8 -*-
                import network
                net =  network.NetWorkClient()
                net.connect({
                        'ssid' : 'KIDS' ,
                        'password' : '12345678'
                    }
                )
        """
        global _on_4g_cb
        if isinstance(data, dict):
          if 'profileidx' in data and isinstance(data['profileidx'],int):
            self.profileidx = data['profileidx']
          elif 'profileidx' in data and not isinstance(data['profileidx'],int):
            raise ValueError("profileidx must be int")
          else:
            pass

          if 'ipType' in data and isinstance(data['ipType'],int):
            self.ipType = data['ipType']
          elif 'ipType' in data and not isinstance(data['ipType'],int):
            raise ValueError('ipType must be int')
          else:
            pass
          
          if 'apn' in data and isinstance(data['apn'],str):
            self.apn = data['apn']
          elif 'apn' in data and not isinstance(data['apn'],str):
            raise ValueError('apn must be str')
          else:
            pass

          if 'username' in data and isinstance(data['username'],str):
            self.username = data['username']
          elif 'username' in data and not isinstance(data['username'],str):
            raise ValueError('username must be str')
          else:
            pass

          if 'password' in data and isinstance(data['password'],str):
            self.password = data['password']
          elif 'password' in data and not isinstance(data['password'],str):
            raise ValueError('password must be str')
          else:
            pass

          if 'authType' in data and isinstance(data['authType'],int):
            self.authType = data['authType']
          elif 'authType' in data and not isinstance(data['authType'],int):
            raise ValueError('authType must be int')
          else:
            pass
        else:
          pass
        
        dc.setCallback(_on_4g_cb)

        return dc.start(self.profileidx,self.ipType,self.apn,self.username,self.password,self.authType)

    def disconnect(self):
        """
        断开网络
        """
        # nm.disconnect()
        pass

    def getType(self):
        """
        获取当前网络类型:

        :param 空:
        :returns: 

            .. list-table::

                * - 返回值
                  - 网络类型
                * - 0
                  - WIFI
                * - 1
                  - 蜂窝网络
                * - 2
                  - 以太网
                * - 3
                  - 未知网络   




        """
        return 1

    def getStatus(self):
        """

        获取当前网络状态

        :param 空:
        :returns: 

          .. list-table::

                * - 返回值
                  - 连接状态
                * - 0
                  - 断开连接中
                * - 1
                  - 断开连接
                * - 2
                  - 连接中
                * - 3
                  - 连接成功   
                * - 4
                  - 获取ip中
                * - 5
                  - 获取ip成功   
                * - 6
                  - 连接失败
                * - 7
                  - 位置状态   


          - ``True``  已连接
          - ``False`` 未连接

        """
        # return nm.getStatus()
        return self._stagecode

    def getInfo(self):
        """

        获取当前网络信息

        :param 空:
        :returns: 返回一个字典，字典信息如下

              .. list-table::

                    * - key名称
                      - value类型
                    * - SSID
                      - 字符串
                    * - IP
                      - 字符串
                    * - MAC
                      - 字符串
                    * - RSSI
                      - Int 

        """
        # return nm.getInfo()
        return None


    def on(self,id,func):
        global _on_4g_cb
        _on_4g_cb = func
        dc.setCallback(_on_4g_cb)
